import Req from '@/api/product'
import {isEmpty} from '@/utils/util'

export default {
  name: 'ProductManagement',
  data() {
    return {
      loading: false,
      searchForm: {
        category: '',
        subCategory: '',
        name: ''
      },
      tableData: [],
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      dialogVisible: false,
      dialogTitle: '新增产品',
      stockInDialogVisible: false,
      stockOutDialogVisible: false,
      formData: {
        productId: '',
        category: '',
        subCategory: '',
        name: '',
        price: 0,
        stock: 0,
        discountFlag: '1',
        discounts: [
          {
            discountValue: 0,
            discountName: '折扣1'
          },
          {
            discountValue: 0,
            discountName: '折扣2'
          },
          {
            discountValue: 0,
            discountName: '折扣3'
          },
        ]
      },
      stockForm: {
        productId: '',
        quantity: 1,
        remark: ''
      },
      formRules: {
        category: [{required: true, message: '请选择类别', trigger: 'change'}],
        subCategory: [{required: true, message: '请选择子类', trigger: 'change'}],
        // price: [{required: true, message: '请输入单价', trigger: 'blur'}],
        // stock: [{required: true, message: '请输入库存', trigger: 'blur'}],
      },
      stockRules: {
        productId: [{required: true, message: '请选择产品', trigger: 'change'}],
        quantity: [{required: true, message: '请输入数量', trigger: 'blur'}]
      },
      categoryOptions: [
        {value: '寿盒', label: '寿盒'},
        {value: '鲜花', label: '鲜花'},
        {value: '烧盘缠', label: '烧盘缠'},
        {value: '服务费', label: '服务费'},
        {value: '寿衣', label: '寿衣'},
        {value: '灵堂', label: '灵堂'},
        {value: '小物件', label: '小物件'},
        {value: '安葬', label: '安葬'},
      ],
      subCategoryOptions: [
        {value: '玉石', label: '玉石', category: '寿盒'},
        {value: '木质', label: '木质', category: '寿盒'},
        {value: '铝材', label: '铝材', category: '寿盒'},
        {value: '花盆', label: '花盆', category: '鲜花'},
        {value: '花圈', label: '花圈', category: '鲜花'},
        {value: '花篮', label: '花篮', category: '鲜花'},
        {value: '花球', label: '花球', category: '鲜花'},
        {value: '心型', label: '心型', category: '鲜花'},
        {value: '天梯', label: '天梯', category: '鲜花'},
        {value: '套装', label: '套装', category: '烧盘缠'},
        {value: '单品', label: '单品', category: '烧盘缠'},
        {value: '烧七', label: '烧七', category: '烧盘缠'},
        {value: '普通遗体', label: '普通遗体', category: '服务费'},
        {value: '特殊遗体', label: '特殊遗体', category: '服务费'},
        {value: '套装', label: '套装', category: '寿衣'},
        {value: '配件', label: '配件', category: '寿衣'},
        {value: '宗教', label: '宗教', category: '寿衣'},
        {value: '贡品', label: '贡品', category: '灵堂'},
        {value: '物品', label: '物品', category: '灵堂'},
        {value: '一次性物品', label: '一次性物品', category: '小物件'},
        {value: '遗像', label: '遗像', category: '小物件'},
        {value: '灵位牌', label: '灵位牌', category: '小物件'},
        {value: '童男女', label: '童男女', category: '小物件'},
        {value: '陪侍用品', label: '陪侍用品', category: '小物件'},
        {value: '属相', label: '属相', category: '小物件'},
        {value: '孝服', label: '孝服', category: '小物件'},
        {value: '骨灰三件套', label: '骨灰三件套', category: '小物件'},
        {value: '寄存瓶位用品', label: '寄存瓶位用品', category: '小物件'},
        {value: '随葬品', label: '随葬品', category: '安葬'},
        {value: '服务', label: '服务', category: '安葬'},
        {value: '海葬', label: '海葬', category: '安葬'},
      ],
      subCategoryOptions2: []
    }
  },
  mounted() {
    this.getList()
  },
  methods: {
    // 获取列表数据
    getList() {
      Req.getProductList({}).then(res => {
        this.tableData = res.data
      })
    },
    // 搜索
    handleSearch() {
      this.pagination.currentPage = 1
      this.getList()
    },
    // 重置搜索
    resetSearch() {
      this.$refs.searchForm.resetFields()
      this.handleSearch()
    },
    // 新增
    handleAdd() {
      this.dialogTitle = '新增产品'
      this.formData = {
        category: '',
        subCategory: '',
        name: '',
        price: 0,
        // stock: 0,
        priceFlag: '0',
        quantityFlag: '0',
        // discountFlag: '0',
        // discounts: [
        //   {
        //     discountValue: 0,
        //     discountName: '折扣1'
        //   },
        //   {
        //     discountValue: 0,
        //     discountName: '折扣2'
        //   },
        //   {
        //     discountValue: 0,
        //     discountName: '折扣3'
        //   },
        // ]
      }
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.productForm && this.$refs.productForm.clearValidate()
      })
    },
    // 编辑
    handleEdit(row) {
      this.dialogTitle = '编辑产品'
      this.formData = JSON.parse(JSON.stringify(row))
      if (isEmpty(this.formData.discounts)) {
        this.formData.discounts = [
          {
            discountValue: 0,
            discountName: '折扣1'
          },
          {
            discountValue: 0,
            discountName: '折扣2'
          },
          {
            discountValue: 0,
            discountName: '折扣3'
          },
        ]
      }

      this.dialogVisible = true

      this.$nextTick(() => {
        this.$refs.productForm && this.$refs.productForm.clearValidate()
      })
    },
    // 提交表单
    handleSubmit() {
      this.$refs.productForm.validate(valid => {
        if (valid) {
          if (!isEmpty(this.formData.productId)) {
            // 编辑
            this.updateProduct()
            this.$message.success('编辑成功')
          } else {
            // 新增

            this.formData.price = this.formData.priceFlag === '1' ? 0 : this.formData.price
            this.formData.discounts = this.formData.discountFlag === '0' ? [] : this.formData.discounts
            console.log(this.formData)
            Req.createProduct(this.formData).then(res => {
              console.log(res)
              this.$message.success('新增成功')
            }).finally(() => {
              this.getList()
            })
          }
          this.dialogVisible = false

        }
      })
    },
    // 入库
    handleStockIn() {
      this.stockForm = {
        productId: '',
        quantity: 1,
        remark: ''
      }
      this.stockInDialogVisible = true
      this.$nextTick(() => {
        this.$refs.stockInForm && this.$refs.stockInForm.clearValidate()
      })
    },
    // 出库
    handleStockOut() {
      this.stockForm = {
        productId: '',
        quantity: 1,
        remark: ''
      }
      this.stockOutDialogVisible = true
      this.$nextTick(() => {
        this.$refs.stockOutForm && this.$refs.stockOutForm.clearValidate()
      })
    },
    // 快速入库
    handleQuickStockIn(row) {
      this.stockForm = {
        productId: row.id,
        quantity: 1,
        remark: ''
      }
      this.stockInDialogVisible = true
      this.$nextTick(() => {
        this.$refs.stockInForm && this.$refs.stockInForm.clearValidate()
      })
    },
    // 快速出库
    handleQuickStockOut(row) {
      this.stockForm = {
        productId: row.id,
        quantity: 1,
        remark: ''
      }
      this.stockOutDialogVisible = true
      this.$nextTick(() => {
        this.$refs.stockOutForm && this.$refs.stockOutForm.clearValidate()
      })
    },
    // 提交入库
    submitStockIn() {
      this.$refs.stockInForm.validate(valid => {
        if (valid) {
          // 模拟入库操作
          this.$message.success('入库成功')
          this.stockInDialogVisible = false
          this.getList()
        }
      })
    },
    // 提交出库
    submitStockOut() {
      this.$refs.stockOutForm.validate(valid => {
        if (valid) {
          const product = this.tableData.find(item => item.id === this.stockForm.productId)
          if (product && product.stock < this.stockForm.quantity) {
            this.$message.warning('库存不足')
            return
          }
          // 模拟出库操作
          this.$message.success('出库成功')
          this.stockOutDialogVisible = false
          this.getList()
        }
      })
    },
    // 分页大小变化
    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.getList()
    },
    // 页码变化
    handleCurrentChange(val) {
      this.pagination.currentPage = val
      this.getList()
    },
    // 折扣开关
    onChangeDiscount(e) {
      console.log('onChangeDiscount', e)
    },
    // 类别下拉框改变
    onChangeCategory(e) {
      console.log('onChangeCategory', e)
      this.subCategoryOptions2 = this.subCategoryOptions.filter(item => item.category === e)
      console.log('subCategoryOptions2', this.subCategoryOptions.filter(item => item.category === e))
    },
    updateProduct() {
      const param = {
        productId: this.formData.productId,
        name: this.formData.name,
        category: this.formData.category,
        subCategory: this.formData.subCategory,
        price: this.formData.price,
      }
      const param2 = {
        productId: this.formData.productId,
        currentStock: this.formData.stock,
        alertThreshold: 10
      }
      const param3 = {
        productId: this.formData.productId,
        discounts: this.formData.discountFlag === '1' ? this.formData.discounts : []
      }
      Promise.all([
        Req.updateProduct(param),
        Req.updateProductInventory(param2),
        Req.updateProductDiscount(param3)
      ]).then(res => {
        console.log(res)
      }).finally(() => {
        this.getList()
      })
    },
    onChangePriceFlag(e) {
      // 是否需要手动输入价格 priceFlag 类型 String （0: 不需要，1: 需要）
      console.log('onChangePriceFlag', e)
      // this.formData.
      this.formData.price = e === '1' ? 0 : this.formData.price
    },
    onChangeQuantity(e) {
      // 是否需要修改数量 quantityFlag 类型 String （0: 不需要，1：需要）

    },
    objectSpanMethod({row, column, rowIndex, columnIndex}) {

      // 处理类别列的合并
      if (columnIndex === 1) {
        if (rowIndex === 0) {
          const categorySpan = this.getCategorySpan(rowIndex)
          return {
            rowspan: categorySpan,
            colspan: 1
          }
        } else {
          const prevRow = this.tableData[rowIndex - 1]
          if (prevRow && prevRow.category === row.category) {
            return {
              rowspan: 0,
              colspan: 0
            }
          } else {
            const categorySpan = this.getCategorySpan(rowIndex)
            return {
              rowspan: categorySpan,
              colspan: 1
            }
          }
        }
      }

      if (columnIndex === 2) {
        if (rowIndex === 0) {
          const subCategorySpan = this.getSubCategory(rowIndex)
          return {
            rowspan: subCategorySpan,
            colspan: 1
          }
        } else {
          const prevRow = this.tableData[rowIndex - 1]
          if (prevRow && prevRow.subCategory === row.subCategory) {
            return {
              rowspan: 0,
              colspan: 0
            }
          } else {
            const subCategorySpan = this.getSubCategory(rowIndex)
            return {
              rowspan: subCategorySpan,
              colspan: 1
            }
          }
        }
      }

      // if (columnIndex === 2) {
      //   // 服务费-普通通体(3行)
      //   if (rowIndex >= 0 && rowIndex <= 2) {
      //     if (rowIndex === 0) return {rowspan: 3, colspan: 1};
      //     return {rowspan: 0, colspan: 0};
      //   }
      //   // 服务费-特殊通体(1行)
      //   if (rowIndex === 3) return {rowspan: 1, colspan: 1};
      //
      //   // 寿衣-套装(2行)
      //   if (rowIndex >= 4 && rowIndex <= 5) {
      //     if (rowIndex === 4) return {rowspan: 2, colspan: 1};
      //     return {rowspan: 0, colspan: 0};
      //   }
      //   // 寿衣-配件(6行)
      //   if (rowIndex >= 6 && rowIndex <= 11) {
      //     if (rowIndex === 6) return {rowspan: 6, colspan: 1};
      //     return {rowspan: 0, colspan: 0};
      //   }
      //   // 寿衣-宗教(2行)
      //   if (rowIndex >= 12 && rowIndex <= 13) {
      //     if (rowIndex === 12) return {rowspan: 2, colspan: 1};
      //     return {rowspan: 0, colspan: 0};
      //   }
      //
      //   // 灵堂-贵品(2行)
      //   if (rowIndex >= 14 && rowIndex <= 15) {
      //     if (rowIndex === 14) return {rowspan: 2, colspan: 1};
      //     return {rowspan: 0, colspan: 0};
      //   }
      //   // 灵堂-一次性物品(1行)
      //   if (rowIndex === 16) return {rowspan: 1, colspan: 1};
      //
      //   // 烧盘缠-套装(1行)
      //   if (rowIndex === 34) return {rowspan: 1, colspan: 1};
      //   // 烧盘缠-单品(8行)
      //   if (rowIndex >= 35 && rowIndex <= 42) {
      //     if (rowIndex === 35) return {rowspan: 8, colspan: 1};
      //     return {rowspan: 0, colspan: 0};
      //   }
      //   // 烧盘缠-统七(1行)
      //   if (rowIndex === 43) return {rowspan: 1, colspan: 1};
      //
      //   // 安葬的子类(各1行)
      //   if (rowIndex >= 44 && rowIndex <= 46) {
      //     return {rowspan: 1, colspan: 1};
      //   }
      // }

    },
    // 获取类别跨度
    getCategorySpan(startIndex) {
      const category = this.tableData[startIndex].category
      let span = 1
      for (let i = startIndex + 1; i < this.tableData.length; i++) {
        if (this.tableData[i].category === category) {
          span++
        } else {
          break
        }
      }
      return span
    },
    // 获取子类跨度
    getSubCategory(startIndex) {
      const subCategory = this.tableData[startIndex].subCategory
      let span = 1
      for (let i = startIndex + 1; i < this.tableData.length; i++) {
        if (this.tableData[i].subCategory === subCategory) {
          span++
        } else {
          break
        }
      }
      return span
    },
  }
}